from database.database import Database
from datetime import datetime

from model.park_location_record import ParkLocationRecord


class ParkLocationRecordTable(Database):
    def __init__(self, platform_id = 0):
        self.table_name = "park_location_records"
        self.platform_id = platform_id

    def insert(self, data: ParkLocationRecord, commit=False):
        sql = self.get_insert_sql_from_obj(data, self.table_name)
        self.execute(sql)
        if commit:
            self.commit()
        return int(self.cursor.lastrowid)

    def exist(self, col_name, value):
        sql = f"select * from {self.table_name} where 1 = 1"
        if self.platform_id > 0:
            sql += f" and `platform_id` = {self.platform_id}"
        sql += f" and `{col_name}` = '{value}' limit 1"
        self.execute(sql)
        result = self.cursor.fetchone()
        if not result:
            return False
        return True

    def query(self, park_id, park_name = ""):
        sql = f"select * from {self.table_name} where 1 = 1"
        if self.platform_id > 0:
            sql += f" and `platform_id` = {self.platform_id}"
        sql += f" and `park_id` = '{park_id}'"
        self.execute(sql)
        records = self.cursor.fetchall()
        if not records:
            if park_name:
                return self.query_by_name(park_name)
            else:
                return ""
            
        result = records[0]
        
        for record in records:
            if park_name == record["park_name"]:
                result = record
                break
            
        return f"{result['park_name']}({result['address']})"

    def query_by_name(self, park_name):
        sql = f"select * from {self.table_name} where 1 = 1"
        if self.platform_id > 0:
            sql += f" and `platform_id` = {self.platform_id}"
        sql += f" and `park_name` = '{park_name}' limit 1"
        self.execute(sql)
        result = self.cursor.fetchone()
        if not result:
            if len(park_name) > 10:
                return self.query_by_name(park_name[0:10])
            elif "停车场" in park_name:
                return self.query_by_name(park_name.replace("停车场", ""))
            elif "车场" in park_name:
                return self.query_by_name(park_name.replace("车场", ""))
            return ""
        return f"{result['park_name']}({result['address']})"
        
    def query_by_code(self, park_code):
        sql = f"select * from {self.table_name} where 1 = 1"
        if self.platform_id > 0:
            sql += f" and `platform_id` = {self.platform_id}"
        sql += f" and `park_code` = '{park_code}' limit 1"
        self.execute(sql)
        result = self.cursor.fetchone()
        if not result:
            return ""
        return f"{result['park_name']}({result['address']})"
